package middleware

import (
	"github.com/zeromicro/go-zero/rest/httpx"
	"gitlab.zhijiasoft.com/paperless-group/saas-common/config"
	"gitlab.zhijiasoft.com/paperless-group/saas-common/enum/errorcode"
	"gitlab.zhijiasoft.com/paperless-group/saas-common/errorx"
	"net/http"
)

// PermissionChecker interface for permission checker
type PermissionChecker interface {
	Check(r *http.Request, w http.ResponseWriter) (*http.Request, bool, error)
	SkipPermissionCheck(r *http.Request, w http.ResponseWriter) (*http.Request, bool, error)
}

type AuthorityMiddleware struct {
	AuthorityConf *config.AuthorityConf
	Checker       PermissionChecker
}

func NewAuthorityMiddleware(checker PermissionChecker, authorityConf *config.AuthorityConf) *AuthorityMiddleware {
	return &AuthorityMiddleware{
		Checker:       checker,
		AuthorityConf: authorityConf,
	}
}

func (m *AuthorityMiddleware) Handle(next http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {

		// 检查全局设置，确认是否要跳过权限检查
		r, skip, err := m.Checker.SkipPermissionCheck(r, w)
		if skip {
			next(w, r)
			return
		}

		// 执行检查
		_, ok, err := m.Checker.Check(r, w)
		if err != nil || !ok {
			httpx.Error(w, errorx.NewCodeError(errorcode.PermissionDenied, "权限不足").WithCode(403))
			return
		}

	}
}
